package mang2many;

import java.util.Iterator;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import util.HibernateUtil;

public class TestMany2Many {
	//保存Groups和Roles
	@Test
	public void testSave()
	{
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		Group group1 = new Group();
		group1.setName("g1");

		Group group2 = new Group();
		group2.setName("g2");

		Group group3 = new Group();
		group3.setName("g3");

		Role role1 = new Role();
		role1.setName("r1");

		Role role2 = new Role();
		role2.setName("r2");

		Role role3 = new Role();
		role3.setName("r3");

		
		group1.getRoles().add(role2);
		group1.getRoles().add(role3);

		group2.getRoles().add(role1);
		group2.getRoles().add(role3);

		group3.getRoles().add(role1);
		group3.getRoles().add(role2);
		
		role1.getGroups().add(group2);
		role1.getGroups().add(group3);

		role2.getGroups().add(group1);
		role2.getGroups().add(group3);

		role3.getGroups().add(group1);
		role3.getGroups().add(group2);

		
		session.save(group1);
		session.save(group2);
		session.save(group3);
		
		tx.commit();
		
	}
	
	//获取Group的所有Roles
	@Test
	public void testRead()
	{
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Group group = (Group)session.get(Group.class, 3);
		System.out.println(group.getName());
		
		Iterator<Role> roles = group.getRoles().iterator();
		while (roles.hasNext())
		{
			Role role = roles.next();
			System.out.println(role.getName());
		}
		session.getTransaction().commit();
		
	}
	
	//取消Group的某个Role
	@Test
	public void testDeleteRole()
	{
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();

		Group group = (Group)session.get(Group.class, 4);
		System.out.println(group.getName());
		
		Iterator<Role> roles = group.getRoles().iterator();
		Role roleToDel = null;
		while (roles.hasNext())
		{
			Role role = roles.next();
			if (role.getName().equals("r2"))
			{
				roleToDel = role;
			}
		}
		
		group.getRoles().remove(roleToDel);
		
		tx.commit();
		
	}
}
